<template>
  <div class="family-member-detail">
    <a-page-header @back="goBack" :title="isEdit ? '编辑成员' : '新增成员'">
    </a-page-header>
    
    <a-form 
      ref="formRef" 
      :model="form" 
      :rules="rules" 
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      class="member-form"
    >
      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item label="姓名" name="name">
            <a-input v-model:value="form.name" placeholder="请输入成员姓名" />
          </a-form-item>
        </a-col>
        
        <a-col :span="12">
          <a-form-item label="性别" name="gender">
            <a-select v-model:value="form.gender" placeholder="请选择性别" style="width: 100%">
              <a-select-option label="男" value="M" />
              <a-select-option label="女" value="F" />
            </a-select>
          </a-form-item>
        </a-col>
        
        <a-col :span="12">
          <a-form-item label="出生日期" name="birthDate">
            <a-date-picker
              v-model:value="form.birthDate"
              placeholder="请选择出生日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </a-form-item>
        </a-col>
        
        <a-col :span="12">
          <a-form-item label="去世日期" name="deathDate">
            <a-date-picker
              v-model:value="form.deathDate"
              placeholder="请选择去世日期（如已去世）"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        
        <a-col :span="24">
          <a-form-item label="简介" name="biography">
            <a-textarea
              v-model:value="form.biography"
              placeholder="请输入成员简介"
              :rows="4"
            />
          </a-form-item>
        </a-col>
        
        <a-col :span="24">
          <a-form-item label="照片URL" name="photoUrl">
            <a-input v-model:value="form.photoUrl" placeholder="请输入照片URL" />
          </a-form-item>
        </a-col>
        
        <a-col :span="12">
          <a-form-item label="经度" name="longitude">
            <a-input-number 
              v-model:value="form.longitude" 
              placeholder="请输入经度" 
              :precision="6" 
              :step="0.000001" 
              style="width: 100%" 
            />
          </a-form-item>
        </a-col>
        
        <a-col :span="12">
          <a-form-item label="纬度" name="latitude">
            <a-input-number 
              v-model:value="form.latitude" 
              placeholder="请输入纬度" 
              :precision="6" 
              :step="0.000001" 
              style="width: 100%" 
            />
          </a-form-item>
        </a-col>
        
        <a-col :span="12">
          <a-form-item label="家族树ID" name="familyTreeId">
            <a-input-number 
              v-model:value="form.familyTreeId" 
              placeholder="请输入家族树ID" 
              :min="1"
              style="width: 100%" 
            />
          </a-form-item>
        </a-col>
        
        <a-col :span="12" v-if="isEdit">
          <a-form-item label="成员ID">
            <a-input v-model:value="form.id" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      
      <div class="form-actions">
        <a-button type="primary" @click="onSubmit" :loading="loading">
          {{ isEdit ? '更新' : '创建' }}
        </a-button>
        <a-button @click="goBack">取消</a-button>
      </div>
    </a-form>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useFamilyStore } from '../stores/family'

export default {
  name: 'FamilyMemberDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const familyStore = useFamilyStore()
    const formRef = ref(null)
    const loading = ref(false)
    
    // 判断是否为编辑模式
    const isEdit = ref(false)
    
    // 表单数据
    const form = ref({
      id: null,
      name: '',
      gender: '',
      birthDate: '',
      deathDate: '',
      biography: '',
      photoUrl: '',
      latitude: null,
      longitude: null,
      familyTreeId: null,
      fatherId: null,
      motherId: null,
      spouseId: null
    })
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入成员姓名', trigger: 'blur' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      familyTreeId: [
        { required: true, message: '请输入家族树ID', trigger: 'blur' }
      ]
    }
    
    // 获取成员详情
    const getMemberDetail = async (id) => {
      try {
        loading.value = true
        // 直接获取特定成员信息
        const response = await api.get(`/members/${id}`)
        if (response?.data?.data) {
          const member = response.data.data
          // 填充表单数据
          form.value = {
            ...form.value,
            ...member
          }
        }
      } catch (error) {
        message.error('获取成员信息失败')
        console.error('获取成员信息失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 初始化
    onMounted(() => {
      const memberId = route.params.id
      if (memberId) {
        isEdit.value = true
        getMemberDetail(memberId)
      } else {
        // 新增成员时，如果URL参数中有familyTreeId，则设置为默认值
        const familyTreeId = route.query.familyTreeId
        if (familyTreeId) {
          form.value.familyTreeId = parseInt(familyTreeId)
        }
      }
    })
    
    // 提交表单
    const onSubmit = async () => {
      try {
        await formRef.value.validate()
        
        loading.value = true
        if (isEdit.value) {
          // 更新成员
          const { loading: updateLoading, run: updateMember } = familyStore.useUpdateMember()
          const result = await updateMember(form.value.id, form.value)
          if (result?.data?.code === 200) {
            message.success('成员更新成功')
            goBack()
          } else {
            message.error(result?.data?.msg || '成员更新失败')
          }
        } else {
          // 创建成员
          const { loading: createLoading, run: createMember } = familyStore.useCreateMember()
          const result = await createMember(form.value)
          if (result?.data?.code === 200) {
            message.success('成员创建成功')
            goBack()
          } else {
            message.error(result?.data?.msg || '成员创建失败')
          }
        }
      } catch (error) {
        message.error(isEdit.value ? '成员更新失败' : '成员创建失败')
        console.error('操作失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }
    
    return {
      formRef,
      loading: loading.value,
      isEdit: isEdit.value,
      form: form.value,
      rules,
      onSubmit,
      goBack
    }
  }
}
</script>

<style scoped>
.family-member-detail {
  padding: 20px;
}

.member-form {
  margin-top: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.a-page-header {
  margin-bottom: 20px;
}
</style>